package com.example.backgroundtask;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

import java.util.concurrent.TimeUnit;


public class ConcurrentSafetyActivity extends AppCompatActivity implements View.OnClickListener {

    private final String TAG = "CSActivity";

    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_concurrent_safety);
        findViewById(R.id.ac_concurrent_safety_volatile_btn).setOnClickListener(this);
        Log.i(TAG,"1");
        handler.post(new Runnable() {
            @Override
            public void run() {
                Log.i(TAG,"2");
                Log.i(TAG,Thread.currentThread().getName());
            }
        });
        try {
            Thread.sleep(1300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.i(TAG,"3");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ac_concurrent_safety_volatile_btn:
                new VolatileDemo().test();
                break;

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * Volatile 可见性
     */
    public  class VolatileDemo {
//        boolean flag = true;
        volatile boolean flag = true;
        public  void test() {
            new Thread(()->{
                Log.i("VolatileDemo",Thread.currentThread().getName()+"\t -----come in");
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                flag = false;
            },"t1").start();

            new Thread(()->{
                Log.i("VolatileDemo",Thread.currentThread().getName()+"\t -----come in");
                while (flag) {

                }
                Log.i("VolatileDemo",Thread.currentThread().getName()+"\t -----flag被设置为false，程序停止");
            },"t2").start();
        }
    }

}